package com.spider.service;

import com.spider.domain.Datasource;
import com.spider.dao.DatasourceDao;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HQJ
 * @since 2021-02-01
 */
@Service
public class DatasourceServiceI extends ServiceImpl<DatasourceDao, Datasource>  {

    public Map<String,Object> test(Datasource datasource){
        boolean b = false;
        String msg = "";
        try{
            Class.forName(datasource.getDriver());
            Connection conn =
                    DriverManager.getConnection(datasource.getUrl(),datasource.getUsername(),datasource.getPassword());
            if(conn!=null){
                b = true;
            }else{
                b = false;
                msg = "用户名或密码错误或数据库不存在";
            }
        }catch (Exception e){
            b = false;
            msg = e.getMessage();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("msg","连接"+(b?"成功":"失败,失败信息:"+msg));
        map.put("is",b);
        return map;
    }

    public List<String> getTableName(Datasource datasource){
        List<String> list = new ArrayList<>();
        try {
            Class.forName(datasource.getDriver());
            Connection conn =
                    DriverManager.getConnection(datasource.getUrl(),datasource.getUsername(),datasource.getPassword());
            if(conn!=null){
                Statement statement = conn.createStatement();
                String sql = "";
                //TODO 数据类型 区别于不同数据库
                sql = "select table_name from information_schema.tables where table_schema = '"+datasource.getDbType()+"'";
                ResultSet rs = statement.executeQuery(sql);
                while(rs.next()){
                    //把数据库表名添加到list集合中
                    list.add(rs.getString("table_name"));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

}
